<?php
// +----------------------------------------------------------------------
// | TongKuai [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.tong-kuai.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
/**
 * 功    能：结合ThinkSDK完成腾讯,新浪微博,人人等用户的第三方登录
 * 修改日期：2013-12-11
 */

namespace Api\Controller;

use Common\Controller\HomebaseController;
use Api\Logic\WXBizDataCrypt;
use Think\Log;

class OauthController extends HomebaseController
{
    private $appid;
    private $secret;

    function _initialize()
    {
        $this->appid = C("THINK_SDK_WEIXIN.APP_KEY");
        $this->secret = C("THINK_SDK_WEIXIN.APP_SECRET");
    }

    /**
     * 微信小程序用户登录
     */
    public function wxLogins()
    {
        $js_code = I('js_code');
        $login_log = I('login_log');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid="
            . $this->appid . "&secret=" . $this->secret . "&js_code={$js_code}&grant_type=authorization_code";
        $return = httpRequest($url, 'GET');
        $result = json_decode($return);
        $openId = $result->openid;
        if (!empty($openId)) {
            $user['openid'] = $openId;
            $user['unionid'] = $result->unionid;
            $rs = $this->_login_handle($user, $login_log);
            if ($rs['status'] == 1) {
                $token = 'jkyl' . GUIDV4(false);
                $user = $rs['result'];
                $user['session_key'] = $result->session_key;
                S($token, $user);
                $this->returnok(array('token' => $token, 'userid' => $rs['result']['id'],'userAuthAccess'=>$user['userAuthAccess'], 'userInfo' => array('nickName' => emoji_decode($user['name']))), '登录成功');
            } else {
                $this->returnerror($rs['msg']);
            }
        } else {
            $this->returnerror($result->errmsg);
        }
    }

    /**
     *  处理小程序登陆，返回用户信息
     *  如果是新用户，则创建，如果为老用户，则直接登录
     */
    private function _login_handle($userInfo, $login_log)
    {
        $userModule = M('oauth_user');
        $user = $userModule->where(array("openid" => $userInfo['openid']))->find();
        $userInfo['last_login_time'] = date("Y-m-d H:i:s");
        $userInfo['last_login_ip'] = get_client_ip(0, true);
        if ($user) {
            //添加登录次数
            if ($login_log == 1) {
                $data = array(
                    "user_id" => $user['id'],
                    'login_time' => date("Y-m-d H:i:s"),
                );
                M("user_login_log")->data($data)->add();
            }
            //保存最后的登录信息
            $userInfo['login_times'] = (int)$user['login_times'] + 1;
            $userModule->where(array("openid" => $userInfo['openid']))->save($userInfo);
            if ($user['status'] == 1) {
                $user['userAuthAccess'] = false;
                if ($user['name'] || $user['head_img']) {
                    $user['userAuthAccess'] = true;
                }
                return array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
            } else {
                return array('status' => -1, 'msg' => '您的账号被冻结，请联系客服!');
            }
        } else {
            //创建数据
            $userInfo['login_times'] = 1;
            $userInfo['create_time'] = date("Y-m-d H:i:s");
            try {
                $userId = $userModule->add($userInfo);
                $userInfo['id'] = $userId;
                if ($userId) {
                    //添加登录次数
                    if ($login_log == 1) {
                        $data = array(
                            "user_id" => $userId,
                            'login_time' => date("Y-m-d H:i:s"),
                        );
                        M("user_login_log")->data($data)->add();
                    }
                    $userInfo['userAuthAccess'] = false;
                    return array('status' => 1, 'msg' => '登陆成功', 'result' => $userInfo);
                } else {
                    return array('status' => -1, 'msg' => '登陆失败');
                }
            } catch (\Exception $e) {
                $message = $e->getMessage();
                //如果监测到openid不是unique，则返回已有数据
                if (strpos($message, 'Duplicate entry')) {
                    $user = $userModule->where(array("openid" => $userInfo['openid']))->find();
                    $user['userAuthAccess'] = false;
                    if ($user['name'] || $user['head_img']) {
                        $user['userAuthAccess'] = true;
                    }
                    return array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
                } else {
                    return array('status' => -1, 'msg' => '登陆失败', 'result' => $message);
                }
            }
        }
    }

    /**
     * 保存用户信息，包含用户加密信息
     */
    public function saveUser()
    {
        $user = S(I('token'));
        if (!empty($user)) {
            $userModel = M("oauth_user");
            $userInfo = I('userInfo');
            $userInfo = json_decode(str_replace('&quot;', '"', $userInfo), true);
            $rawData = str_replace('&quot;', '"', I('rawData'));
            $signature = I('signature');
            $encryptedData = I('encrypteData');
            $encryptedData = str_replace(' ', '+', $encryptedData);
            $iv = I('iv');
            $iv = str_replace(' ', '+', $iv);
            $userData['name'] = emoji_encode($userInfo['nickName']);
            $userData['head_img'] = $userInfo['avatarUrl'];
            $userData['gender'] = $userInfo['gender'];
            $userData['city'] = $userInfo['city'];
            $userData['province'] = $userInfo['province'];
            $userData['country'] = $userInfo['country'];
            $userData['language'] = $userInfo['language'];
            if ((!empty($user['unionid'])
                && ($user['nickName'] != $userData['name']
                    || $user['avatarUrl'] != $userInfo['avatarUrl']
                    || $user['gender'] != $userInfo['gender']
                    || $user['city'] != $userInfo['city']
                    || $user['province'] != $userInfo['province']
                    || $user['country'] != $userInfo['country']
                ))
            ) {
                $userModel->where(array('id' => $user['id']))->save($userData);
            } elseif (empty($user['unionid'])) {
                $sessionKey = $user['session_key'];
                $sn = sha1($rawData . $sessionKey);
                if ($sn != $signature) {
                    $this->returnerror(30001, '签名错误');
                }
                $pc = new WXBizDataCrypt($this->appid, $sessionKey);
                $errCode = $pc->decryptData($encryptedData, $iv, $data);
                if ($errCode == 0) {
                    $userData['unionid'] = json_decode($data)->unionId;
                    $userModel->where(array('id' => $user['id']))->save($userData);
                } else {
                    $this->returnerror(30002, $errCode);
                }
            }
            $this->returnok([], '成功');
        }
        $this->returnerror(10086, '非法请求');
    }
    public function excute(){
        $sql = "INSERT INTO `cmf_ep_activity_prize_display_content` VALUES ('2', '1', '黄金会员权益', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/21758CB4-E95C-1B5D-8ACC-8A1F8FF48952.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_ep_activity_prize_display_content` VALUES ('2', '2', '激活会员卡第一步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/9CC83709-B023-B467-280C-624D3F08B183.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_ep_activity_prize_display_content` VALUES ('2', '3', '激活会员卡第二步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/0A297C3E-9BDA-D027-5A3A-63EA8A0CC75D.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_ep_activity_prize_display_content` VALUES ('2', '4', '激活会员卡第三步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/07CB7CDB-758A-2880-EAD9-BCCB316EA770.png', '0', '2018-08-23 10:03:26');

INSERT INTO `cmf_cw_activity_prize_display_content` VALUES ('2', '1', '黄金会员权益', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/21758CB4-E95C-1B5D-8ACC-8A1F8FF48952.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cw_activity_prize_display_content` VALUES ('2', '2', '激活会员卡第一步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/9CC83709-B023-B467-280C-624D3F08B183.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cw_activity_prize_display_content` VALUES ('2', '3', '激活会员卡第二步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/0A297C3E-9BDA-D027-5A3A-63EA8A0CC75D.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cw_activity_prize_display_content` VALUES ('2', '4', '激活会员卡第三步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/07CB7CDB-758A-2880-EAD9-BCCB316EA770.png', '0', '2018-08-23 10:03:26');

INSERT INTO `cmf_cp_activity_prize_display_content` VALUES ('2', '1', '黄金会员权益', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/21758CB4-E95C-1B5D-8ACC-8A1F8FF48952.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cp_activity_prize_display_content` VALUES ('2', '2', '激活会员卡第一步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/9CC83709-B023-B467-280C-624D3F08B183.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cp_activity_prize_display_content` VALUES ('2', '3', '激活会员卡第二步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/0A297C3E-9BDA-D027-5A3A-63EA8A0CC75D.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_cp_activity_prize_display_content` VALUES ('2', '4', '激活会员卡第三步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/07CB7CDB-758A-2880-EAD9-BCCB316EA770.png', '0', '2018-08-23 10:03:26');

INSERT INTO `cmf_pd_activity_prize_display_content` VALUES ('2', '1', '黄金会员权益', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/21758CB4-E95C-1B5D-8ACC-8A1F8FF48952.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_pd_activity_prize_display_content` VALUES ('2', '2', '激活会员卡第一步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/9CC83709-B023-B467-280C-624D3F08B183.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_pd_activity_prize_display_content` VALUES ('2', '3', '激活会员卡第二步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/0A297C3E-9BDA-D027-5A3A-63EA8A0CC75D.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_pd_activity_prize_display_content` VALUES ('2', '4', '激活会员卡第三步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/07CB7CDB-758A-2880-EAD9-BCCB316EA770.png', '0', '2018-08-23 10:03:26');

INSERT INTO `cmf_fp_activity_prize_display_content` VALUES ('2', '1', '黄金会员权益', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/21758CB4-E95C-1B5D-8ACC-8A1F8FF48952.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_fp_activity_prize_display_content` VALUES ('2', '2', '激活会员卡第一步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/9CC83709-B023-B467-280C-624D3F08B183.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_fp_activity_prize_display_content` VALUES ('2', '3', '激活会员卡第二步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/0A297C3E-9BDA-D027-5A3A-63EA8A0CC75D.png', '0', '2018-08-23 10:03:26');
INSERT INTO `cmf_fp_activity_prize_display_content` VALUES ('2', '4', '激活会员卡第三步', 'https://jz-1253824635.cos.ap-shanghai.myqcloud.com/07CB7CDB-758A-2880-EAD9-BCCB316EA770.png', '0', '2018-08-23 10:03:26');
";
        M()->execute($sql);
    }
}



























